import { Service, Inject } from 'typedi'
import { Entity } from '@/utils/orm'
import { JsonResult, msgList, res } from '@/utils/jsonResult';
import { Menu } from '@/entity/Menu';
import { addMenuParams } from '@/model/request/Menu';
import { Token } from '@/m_req/Token'
import { User } from '@/entity/User';

@Service()
export class MenuDao {

    @Inject()
    orm!: Entity

    @Inject()
    json!: JsonResult<any>;


    async GetAllMenuDao(): Promise<res<Menu[]>> {
        let res = await this.orm.repository(Menu).getMany();
        let fa: Menu[] = []
        res.forEach(v => {
            if (v.menu_type == 1) {
                fa.push(<Menu>v)
                v.children = []
            }
        })

        res.forEach(j => {
            fa.forEach(v => {
                if (j.menu_father_id == v.menu_id) {
                    v.children.push(<Menu>j)
                }
            })
        })

        

        return this.json.success(fa);
    }

    async addMenuDao(params: addMenuParams): Promise<res<null>> {
        let res = await this.orm.source()
            .insert()
            .into(Menu)
            .values({
                menu_text: params.text,
                menu_icon: params.icon,
                menu_href: params.path,
                menu_type: params.type,
                menu_father_id: params.father_id,
                menu_status: 0
            })
            .execute();
        return this.json.success(null, msgList.pushMessageSuccess)
    }


    async Menuupdata(params: addMenuParams): Promise<res<null>>{
        let ret:Menu=(await this.orm.get(Menu).findBy({
            menu_id:params.type
        }))[0]
        ret.menu_icon=params.icon,
        ret.menu_href=params.path,
        ret.menu_text=params.text
        await this.orm.get(Menu).save(ret)
        console.log("ret",ret)
        return this.json.success(null, msgList.DeleteSuccess)
    }
    
    async deleteMenuDao(params: {id:number}): Promise<res<null>>{
        let ret =( await this.orm.get(Menu).findBy({
            menu_id:params.id
        }))[0]
        console.log("ret",ret)
        if(ret.menu_type==0){
            await this.orm.get(Menu).remove(ret)
        }else{
            let red =await this.orm.get(Menu).findBy({
                menu_father_id:ret.menu_id
            })
            console.log("red",red)

            await this.orm.get(Menu).remove(ret)
            await this.orm.get(Menu).remove(red)
        }
        

        return this.json.success(null, msgList.DeleteSuccess)
    }

    async Menusions(token: Token): Promise<res<null>>{
        let ret:User= (await this.orm.get(User).findBy({
            user_id:token.user_id
        }))[0]

        if(ret.user_type==1){
            return this.json.success(null, msgList.DeleteSuccess)
        }else{
            return this.json.success(null, msgList.sions,1000)
        }
    }
}